package ldh.im.fxgui.pane;

import javafx.scene.Node;
import javafx.scene.text.Text;
import javafx.scene.text.TextAlignment;
import javafx.scene.text.TextFlow;
import ldh.im.dto.enums.MessageType;
import ldh.im.fxbase.data.pojo.ImMessage;
import ldh.im.fxbase.richtext.ImTextPane;
import ldh.im.fxbase.richtext.TextItem;
import ldh.im.fxbase.util.ImRichTextUtil;
import ldh.im.fxbase.util.ParamUtil;

import java.util.List;

public class RichTextMessagePane extends BaseMessagePane {

    @Override
    public Node createPane(ImMessage message, boolean isReceive, boolean isRef) {
        if (message.getMessageType() != MessageType.RichText) {
            throw new RuntimeException("不支持这种消息类型" + message.getMessageType());
        }

        TextAlignment textAlignment = TextAlignment.LEFT; //isReceive ? TextAlignment.LEFT : TextAlignment.RIGHT;

        if (!isRef) {
            ImTextPane textFlow = new ImTextPane(textAlignment);
            textFlow.setWrappingWidth(ParamUtil.MESSAGE_WIDTH);
            textFlow.setImContent(message.getContent());

            buildPopup(textFlow, message);

//            textFlow.getStyleClass().add("im-message-content-pane");

            return textFlow;
        } else {
            return createRefNode(message);
        }
    }

    private TextFlow createRefNode(ImMessage message) {
        TextFlow textFlow = new TextFlow();
        String content = message.getContent();
        List<Object> objects = ImRichTextUtil.split(content);
        for(Object obj : objects) {
            if (obj instanceof TextItem) {
                TextItem textItem = (TextItem) obj;
                textFlow.getChildren().add(textItem.createNode());
            } else {
                String s = obj.toString();
                if (s.equals("")) continue;
                textFlow.getChildren().add(new Text(s));
            }
        }
        return textFlow;
    }
}
